<template>
  <div class="course-list-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline" size="mini">

      <!-- 所属分类：级联下拉列表 -->
      <!-- 一级分类 -->
      <el-form-item>
        <el-select
          v-model="searchParam.categoryParentId"
          placeholder="请选择一级分类"
          @change="subjectLevelOneChanged">
          <el-option
            v-for="category in categoryParentList"
            :key="category.id"
            :label="category.name"
            :value="category.id"/>
        </el-select>

        <!-- 二级分类 -->
        <el-select
          v-model="searchParam.categoryId"
          @change="selectChange()"
          placeholder="请选择二级分类">
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"/>
        </el-select>
      </el-form-item>

      <!-- 讲师姓名 -->
      <el-form-item>
        <el-input v-model="searchParam.teacherName" placeholder="讲师姓名" show-word-limit clearable maxlength="20"/>
      </el-form-item>

      <!-- 课程名称 -->
      <el-form-item>
        <el-input v-model="searchParam.courseName" placeholder="课程名称" show-word-limit clearable maxlength="50"/>
      </el-form-item>

      <!-- 课程级别 -->
      <el-form-item>
        <el-select
          v-model="searchParam.level"
          placeholder="请选择课程级别">
          <el-option
            v-for="level in levels"
            :key="level.value"
            :label="level.label"
            :value="level.value"/>
        </el-select>
      </el-form-item>

      <!-- 课程状态 -->
      <el-form-item>
        <el-select
          v-model="searchParam.status"
          placeholder="请选择课程状态">
          <el-option
            v-for="status in statuses"
            :key="status.value"
            :label="status.label"
            :value="status.value"/>
        </el-select>
      </el-form-item>

      <!-- 课程发布时间 -->
      <el-form-item prop="date" label="发布时间：">
        <el-date-picker
          v-model="date"
          type="daterange"
          align="right"
          unlink-panels
          value-format="yyyy-MM-dd"
          range-separator="至 "
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>

      <el-button type="primary" icon="el-icon-search" @click="fetchData()" size="mini">查询</el-button>
      <el-button type="warning" icon="el-icon-refresh" @click="resetData()" size="mini">清空</el-button>
    </el-form>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      highlight-current-row
      row-class-name="myClassList">

      <el-table-column
        label="序号"
        width="70"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="课程信息" width="470" align="center">
        <template slot-scope="scope">
          <div class="info">
            <div class="pic">
              <img :src="scope.row.cover" alt="scope.row.name" width="150px">
            </div>
            <div class="title">
              <h5>{{ scope.row.courseName }}</h5>
              <p>{{'授课讲师：'+ scope.row.teacherName }}</p>
              <p>{{ scope.row.lessonSum }}课时</p>
            </div>
          </div>

        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.gmtCreate.substr(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.gmtModified.substr(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column label="价格" width="100" align="center" >
        <template slot-scope="scope">
          <el-tag v-if="Number(scope.row.price) === 0" type="success">免费</el-tag>
          {{ Number(scope.row.price) !== 0 ? '¥' + scope.row.price.toFixed(2) : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="buyCount" label="付费人数" width="80" align="center" >
        <template slot-scope="scope">
          {{ scope.row.buySum }}人
        </template>
      </el-table-column>

      <el-table-column prop="status" label="课程级别" width="80" align="center" >
        <template slot-scope="scope">
          <el-tag type="primary" v-if="scope.row.level === 0 ">入门</el-tag>
          <el-tag type="success" v-if="scope.row.level === 1 ">初级</el-tag>
          <el-tag type="warning" v-if="scope.row.level === 2 ">中级</el-tag>
          <el-tag type="danger" v-if="scope.row.level === 3 ">高级</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="课程状态" width="80" align="center" >
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'warning' : 'success'">{{ scope.row.status === 1 ? '未发布' : '已发布' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === 0" type="danger" size="mini" icon="el-icon-close" @click="pullCourse(scope.row.courseId)">下架课程</el-button>
          <el-button v-if="scope.row.status === 1" type="primary" size="mini" icon="el-icon-upload2" @click="pushCourse(scope.row.courseId)">发布课程</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="fetchData"
    />

  </div>
</template>

<script>
  import { getPageList,updateCourseStatus } from '@/api/course'
  import { getAllCategoryNestedList } from '@/api/category'

  export default {
    data() {
      return {
        date: '', //日期
        pickerOptions: {
          //不可选择当天以后日期
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6;
          },

          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          },]
        },
        listLoading: true, // 是否显示loading信息
        list: null, // 数据列表
        total: 0, // 总记录数
        page: 1, // 页码
        limit: 5, // 每页记录数
        searchParam: {
          categoryParentId: '',
          categoryId: '',
          courseName: '',
          teacherName:'',
          level: '',
          status: '',
          teacherId: '',
          begin: '',
          end: ''
        },
        categoryParentList: [], // 一级分类列表
        categoryList: [], // 二级分类列表
        // 课程级别
        levels: [
          {value: 0, label :"入门"}, {value: 1, label: "初级"},
          {value: 2, label: "中级"}, {value: 3, label: "高级"}
        ],
        // 课程状态
        statuses: [
          {value: 0, label: "已发布"}, {value: 1, label: "未发布"}
        ]
      }
    },

    methods:{
      //强制刷新视图，解决级联选择框无法选择
      selectChange(){
        this.$forceUpdate()
      },

      fetchData(page = 1) {
        if (this.date){
          this.searchParam.begin = this.date[0]
          this.searchParam.end = this.date[1]
        }
        // 当点击分页组件的切换按钮的时候，会传输一个当前页码的参数page
        // 解决分页无效问题
        this.page = page
        this.listLoading = true
        getPageList(this.page, this.limit,this.searchParam).then(result => {
          if (result.success === true) {
            this.list = result.data.rows
            this.total = result.data.total
          }
          this.listLoading = false
        })
      },

      initCategoryList() {
        getAllCategoryNestedList().then(result => {
          this.categoryParentList = result.data.items
        })
      },

      subjectLevelOneChanged(value) {
        for (let i = 0; i < this.categoryParentList.length; i++) {
          if (this.categoryParentList[i].id === value) {
            this.categoryList = this.categoryParentList[i].children
            this.searchParam.categoryId = ''
          }
        }
      },

      resetData() {
        this.date = ''
        this.searchParam = {}
        this.categoryList = [] // 二级分类列表
        this.fetchData()
      },

      //下架课程
      pullCourse(courseId){
        this.$confirm('此操作将下架该课程？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return updateCourseStatus(courseId,1)
        }).then(result => { // 如果上一个then成功则执行此处的then回调
          if (result.code === 20000){
            this.fetchData()
            this.$message({
              type: 'success',
              message: '下架成功！'
            })
          }
        }).catch((response) => {
          if (response === 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消下架！'
            })
          }
        })
      },

      //上架课程
      pushCourse(courseId){
        this.$confirm('此操作将上架该课程？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return updateCourseStatus(courseId,0)
        }).then(result => { // 如果上一个then成功则执行此处的then回调
          if (result.code === 20000){
            this.fetchData()
            this.$message({
              type: 'success',
              message: '上架成功！'
            })
          }
        }).catch((response) => {
          if (response === 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消上架！'
            })
          }
        })
      }
    },

    created() { // 当页面加载时获取数据
      this.fetchData()
      // 初始化分类列表
      this.initCategoryList()
    },


  }
</script>

<style scoped>
  .course-list-container{
    margin-top: 20px;
    margin-left: 15px;
  }
  .myClassList .info {
    width: 450px;
    overflow: hidden;
  }
  .myClassList .info .pic {
    width: 150px;
    height: 95px;
    overflow: hidden;
    float: left;
  }
  .myClassList .info .pic a {
    display: block;
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .myClassList .info .pic img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .myClassList td .info .title {
    width: 280px;
    float: right;
    height: 90px;
  }
  .myClassList td .info .title h5 {
    display: block;
    font-size: 15px;
    margin-top: 0px;
    height: 48px;
    line-height: 24px;
    overflow: hidden;
    color: #409EFF;
    margin-bottom: 5px;
  }
  .myClassList td .info .title p {
    font-size: 14px;
    margin: 0px;
    color: #818181;
  }
</style>
